import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class SM4Test {
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
        String password = "password";
        String candidate = null;
        PBKDF2HexFormatter formatter = new PBKDF2HexFormatter();
        int iterations = 1000;
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[8];
        sr.nextBytes(salt);
        PBKDF2Parameters p = new PBKDF2Parameters("HmacSHA1", "ISO-8859-1", salt, iterations);
        PBKDF2Engine e = new PBKDF2Engine(p);
        p.setDerivedKey(e.deriveKey(password, 16));
        candidate = formatter.toString(p);
        System.out.println(candidate);
        byte[] key = p.getDerivedKey();

        String keyStr = BinTools.bin2hex(key);
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("src/main/resources/key.txt"));
            out.write(keyStr);
            out.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

//        String content = "jinrongshujuanquan1234567890";
//        SymmetricCrypto sm4 = SmUtil.sm4(key);
//        String encryptHex = sm4.encryptHex(content);
//        String decryptStr = sm4.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
//        System.out.println(encryptHex + "\r\n" + decryptStr);

        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        byte[] iv = new byte[16];
        sr.nextBytes(iv);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        SM4 sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, key, ivParameterSpec.getIV());
        byte[] content = Files.readAllBytes(Paths.get("src/main/resources/table.png"));
        byte[] cipher = sm4.encrypt(content);
        byte[] decrypted = sm4.decrypt(cipher);
        Files.write(Paths.get("src/main/resources/decrypted.png"), decrypted);
    }
}
